package com.hslxy.niukewang.util;

import org.apache.commons.lang3.CharUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

@Component
public class SensitiveFilter {

    private static final Logger logger = LoggerFactory.getLogger(SensitiveFilter.class);

//    替换符
    private static final String REPLACEMENT = "***";

//  根节点
    private TreeNode root = new TreeNode();

    @PostConstruct
    public void init() {
        try (
                InputStream is = this.getClass().getClassLoader().getResourceAsStream("sensitive-words.txt");
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        ){
            String keyword;
            while ((keyword = reader.readLine()) != null){
                this.addKeyword(keyword);
            }
        }catch (IOException e){
            logger.error("加载敏感词文件失败:"+e.getMessage());
        }
    }

    private void addKeyword(String keyword){
        TreeNode node = root;
        for (int i = 0; i < keyword.length(); i++) {
            char c = keyword.charAt(i);
            TreeNode subNode = node.getSubNode(c);
            if(subNode == null){
                subNode = new TreeNode();
                node.addSubNode(c, subNode);
            }
            node = subNode;
            if (i == keyword.length()-1){
                node.setKeywordEnd(true);
            }
        }
    }

//    返回过滤后的文本
    public String filter(String text){
        if(StringUtils.isBlank(text)){
            return null;
        }
//        指针1
        TreeNode node = root;
//        指针2
        int begin = 0;
//        指针3
        int position = 0;
        StringBuilder sb = new StringBuilder();
        while (position < text.length()){
            char c = text.charAt(position);
            if(isSymbol(c)){
                if(node == root){
                    sb.append(c);
                    begin++;
                }
                position++;
                continue;
            }
//            检查下一个节点
            node = node.getSubNode(c);
            if (node == null){
//                不是敏感词
                sb.append(text.charAt(begin));
                node = root;
                begin++;
                position = begin;
            }else {
//                是敏感词
                if(node.isKeywordEnd()){
                    sb.append(REPLACEMENT);
                    position++;
                    begin = position;
                    node = root;
                }else {
                    position++;
                }
            }
        }
        sb.append(text.substring(begin));
        return sb.toString();
    }

//  判断是不是特殊符号
    private boolean isSymbol(Character c){
        return !CharUtils.isAsciiAlphanumeric(c) && (c < 0x2E80 || c > 0x9FFF);
    }

    private class TreeNode{
//        关键词结束的标识
        private boolean isKeywordEnd = false;
//        子节点(key下级节点字符)
        private Map<Character, TreeNode> subNodes = new HashMap<>();
        public boolean isKeywordEnd() {
            return isKeywordEnd;
        }
        public void setKeywordEnd(boolean keywordEnd){
            isKeywordEnd = keywordEnd;
        }

//        添加子节点
        public void addSubNode(Character c, TreeNode node){
            subNodes.put(c, node);
        }

//        获取子节点
        public TreeNode getSubNode(Character c){
            return subNodes.get(c);
        }
    }
}
